<?php
namespace Snitso\IO\Blocking;

class Worker
{
    /**
     * @var resource $socket
     */
    protected $socket;

    /**
     * @var \Closure
     */
    public $onConnect;

    /**
     * @var \Closure
     */
    public $onReceive;

    public function __construct(string $localSocket)
    {
        $socket = stream_socket_server($localSocket, $errno, $errstr);

        if (! $socket) {
            echo $errstr . PHP_EOL;
            exit;
        }

        $this->socket = $socket;
    }

    public function start()
    {
        $this->accept();
    }

    protected function accept()
    {
        while (true) {
            $conn = stream_socket_accept($this->socket);

            if ($conn === false) {
                echo '连接失败' . PHP_EOL;
                exit;
            }

            ($this->onConnect)($this, $conn);

            $data = fread($conn, 1024);

            ($this->onReceive)($this, $conn, $data);

            fclose($conn);
        }

        fclose($this->socket);
    }

    public function send($conn, string $content)
    {
        $response = "HTTP/1.1 200 OK\r\n";
        $response .= "Content-Type: text/html;charset=UTF-8\r\n";
        $response .= "Connection: keep-alive\r\n";
        $response .= "Content-length: ".strlen($content)."\r\n\r\n";
        $response .= $content;
        fwrite($conn, $response);
    }
}